package org.jeecg.modules.wx.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.system.entity.SysThirdAccount;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.model.ThirdLoginModel;
import org.jeecg.modules.system.service.ISysThirdAccountService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.wx.service.WxLoginService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/wechat/api")
public class UserController {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysThirdAccountService sysThirdAccountService;
    @Autowired
    private BaseCommonService baseCommonService;
    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private WxLoginService loginService;

    @ApiOperation("登录")
    @PostMapping("/ma/login")
    public Result<Object> login(
            @ApiParam("微信用户临时登陆code") @NotBlank
            @RequestParam String code) {
        try {
            WxMaJscode2SessionResult result = wxMaService.jsCode2SessionInfo(code);
            String openid = result.getOpenid();

            SysUser sysUser = loginService.wxLogin(openid);

            String token = saveToken(sysUser);
            JSONObject obj = new JSONObject(new LinkedHashMap<>());
            obj.put("token", token);
            obj.put("openid",openid);
            obj.put("userInfo", sysUser);

            LoginUser loginUser = new LoginUser();
            BeanUtils.copyProperties(sysUser, loginUser);
            baseCommonService.addLog("用户名: " + sysUser.getRealname() + ",登录成功！", CommonConstant.LOG_TYPE_1, null,loginUser);

            return Result.ok(obj);
        } catch (WxErrorException e){
            return Result.error(e.getError().getErrorMsg());
        }catch (Exception e) {
            return Result.error(1000,e.getMessage());
        }
    }

    @ApiOperation("注册")
    @PostMapping("/ma/register")
    public Result<Object> register(@RequestBody ThirdLoginModel thirdLoginModel) {
        try {
            String openid = thirdLoginModel.getUuid();
            String username = thirdLoginModel.getUsername();
            String birthday = thirdLoginModel.getBirthday();
            if(StringUtils.isBlank(birthday)){
                thirdLoginModel.setBirthday("1950-01-01");
            }
            if(StringUtils.isBlank(username)){
                username = "微信用户"+ RandomStringUtils.random(5, false, true);
                thirdLoginModel.setUsername(username);
            }
            SysThirdAccount thirdAccount = sysThirdAccountService.getOneByThirdUserUuid(openid);
            if(null == thirdAccount) {
                thirdAccount = sysThirdAccountService.saveThirdUser(thirdLoginModel);
            }else{
                thirdAccount.setPhone(thirdLoginModel.getPhone());
                thirdAccount.setAvatar(thirdLoginModel.getAvatar());
                thirdAccount.setRealname(thirdLoginModel.getUsername());
                sysThirdAccountService.updateById(thirdAccount);
            }
            thirdAccount.setBirthday(thirdLoginModel.getBirthday());
            SysUser sysUser = loginService.getSysUserByThird(thirdAccount);
            String token = saveToken(sysUser);
            JSONObject obj = new JSONObject(new LinkedHashMap<>());
            obj.put("token", token);
            obj.put("userInfo", sysUser);
            return Result.ok(obj);

        } catch (Exception e) {
            return Result.error(1000,e.getMessage());
        }
    }

    @SneakyThrows
    @PostMapping("/ma/phone")
    public Result phone(@RequestBody Map codeMap) {
        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo("" + codeMap.get("code"));

        return Result.ok(phoneNoInfo);
    }

    private String saveToken(SysUser user) {
        // 生成token
        String token = JwtUtil.sign(user.getUsername(), user.getPassword());
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        // 设置超时时间
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        return token;
    }
}
